﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UFrameWork
{
    /// <summary>
    /// 控制台命令处理
    /// </summary>
    public class ConsoleCmd
    {
        /// <summary>
        /// 命令map
        /// </summary>
        private static Dictionary<string, Action<string[]>> HandleMap = new Dictionary<string, Action<string[]>>();

        /// <summary>
        /// 处理控制台命令
        /// 必须在注册完命令之后启动处理
        /// </summary>
        public static void Handle()
        {
            string input,key = string.Empty;
            string[] inArray;
            while (true)
            {
                input = Console.ReadLine().Replace("  "," ");

                inArray = input.Split(' ');

                if (string.IsNullOrEmpty(inArray[0])) continue;

                key = inArray[0].Trim().ToLower();

                if (!HandleMap.ContainsKey(key))
                {
                    Console.WriteLine("unknown cmd!");
                    continue;
                }

                try
                {
                    HandleMap[key](inArray);
                }
                catch (Exception e)
                {
                    Console.WriteLine("rund cmd error!");
                    Console.WriteLine(e);
                }
            }
        }

        /// <summary>
        /// 注册命令处理委托
        /// </summary>
        /// <param name="key">命令,多个key使用|分割</param>
        /// <param name="handle">委托函数</param>
        public static void Register(string key, Action<string[]> handle)
        {
            key = key.Trim().ToLower();

            string[] keys = key.Split('|');

            foreach (string k in keys)
            {
                if (!HandleMap.ContainsKey(k))
                {
                    HandleMap[k] = handle;
                }
                else
                {
                    HandleMap[k] += handle;
                }
            }
        }
    }
}